import {
  OPCUAClient,
  ClientSubscription,
  AttributeIds,
  TimestampsToReturn,
  ClientMonitoredItem,
  resolveNodeId
} from 'node-opcua'

import { BrowserWindow } from 'electron'

const endpointUrl = 'opc.tcp://localhost:4840' // 你的 OPC UA 地址
const nodeIdsToMonitor = ['ns=1;s=Temperature', 'ns=1;s=Angle', 'ns=1;s=Vacuum', 'ns=1;s=Magnetism']

async function subscribeOPCUA(mainWindow: BrowserWindow): Promise<void> {
  const client = OPCUAClient.create({
    endpointMustExist: false
  })

  try {
    await client.connect(endpointUrl)
    const session = await client.createSession()
    const subscription = ClientSubscription.create(session, {
      requestedPublishingInterval: 1000,
      requestedMaxKeepAliveCount: 10,
      requestedLifetimeCount: 30,
      maxNotificationsPerPublish: 100,
      publishingEnabled: true,
      priority: 10
    })

    console.log('OPC UA Connected and Subscribed')

    for (const nodeId of nodeIdsToMonitor) {
      const itemToMonitor = {
        nodeId: resolveNodeId(nodeId),
        attributeId: AttributeIds.Value
      }

      const monitoredItem = ClientMonitoredItem.create(
        subscription,
        itemToMonitor,
        {
          samplingInterval: 100,
          discardOldest: true,
          queueSize: 10
        },
        TimestampsToReturn.Both
      )

      monitoredItem.on('changed', (dataValue) => {
        const value = dataValue.value.value
        console.log(`${nodeId} = ${value}`)
        if (mainWindow) {
          mainWindow.webContents.send('data-changed', {
            nodeId,
            value
          })
        }
      })
    }
  } catch (err) {
    console.error('OPC UA Connection failed:', err)
  }
}

export { subscribeOPCUA as connectOPCUAAndSubscribe }
